package search;

import java.util.Arrays;

/**
 * @Author leecho
 * @Date: 2021/10/21 11:12
 * @Version 1.0
 */


/*
* 思路
* - 先创建一个斐波那契数组
*   - 1、1、2、3、5...
* - 根据原数组找到在斐波拉契数列中最近的值
* - 创建一个临时数组，大小为在斐波拉契中找到的值，不够的以数组的最后一位进行补充
*   - f[k] = f[k-1] + f[k-2]
* - 不断与新的中点就行比较，找打了返回mid和high中较小的那一个
*       - 因为临时数组的后面可能是补充的所以要返回较小的下标，为找到的数字
* */
public class FibonacciSearch {
    public static int MaxSize = 20;

    public static void main(String[] args) {
        FibonacciSearch fibonacciSearch = new FibonacciSearch();
        int[] arr = {1,2,3,4,5,6,7,8,9,10,11,12,13};

        int i = fibonacciSearch.fibonacciSearch(arr, 6);
        System.out.println(i);
    }

    public int[] fi(){
        int[] fi = new int[MaxSize];
        fi[0] = 1;
        fi[1] = 1;

        for (int i = 2; i < fi.length; i++) {
            fi[i] = fi[i-1] + fi[i-2];
        }

        return fi;
    }

    public int fibonacciSearch(int[] arr, int findVal){
        int low = 0;
        int high = arr.length - 1;
        int k = 0;

        int[] fi = fi();

        while (high > fi[k] - 1){
            k++;
        }

        int[] temp = Arrays.copyOf(arr,fi[k]);
        for (int i = high+1; i < temp.length; i++) {
            temp[i] = arr[high];
        }

        while (high >= low){
            int mid = low + fi[k-1] - 1;
            if (findVal > temp[mid]){
                low = mid + 1;
                k -= 2;
            } else if (findVal < temp[mid]){
                high = mid - 1;
                k--;
            } else {
                return Math.min(mid, high);
            }
        }
        return -1;
    }
}
